package com.fone.player.play.fragment;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.fone.player.R;
import com.fone.player.activity.BaseFragment;
import com.fone.player.client.Callback;
import com.fone.player.client.DramaRst;
import com.fone.player.client.DramaRst.Cnt;
import com.fone.player.client.DramaRst.Cnts;
import com.fone.player.client.Error;
import com.fone.player.client.Request;
import com.fone.player.client.VgdetailRst.From;
import com.fone.player.play.ChangeVideoEvent;
import com.fone.player.play.FonePlayerActivity;
import com.fone.player.play.VideoPlayerMessage;
import com.fone.player.play.adapter.GridSeriesItemAdapter;
import com.fone.player.play.adapter.GridSeriesTabItemAdapter;
import com.fone.player.play.adapter.ListSeriesItemAdapter;
import com.fone.player.storage.StorageModule;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.util.ScreenUtil;
import com.fone.player.view.ColorBallProgressView;
import com.fone.player.view.NoScrollGridView;

import de.greenrobot.event.EventBus;

/**
 * 剧集
 * 
 * @author kongxiaojun
 * @since 2014-4-21
 * 
 */
@SuppressLint("ValidFragment")
public class VideoSeriesFragment extends BaseFragment {

	private static final String TAG = "VideoSeriesFragment";

	private View contentView;
	private NoScrollGridView seriesTab;
	private GridView seriesGridView;
	private ListView seriesListView;
	private GridSeriesTabItemAdapter seriesTabItemAdapter;
	private GridSeriesItemAdapter gridSeriesItemAdapter;
	private ListSeriesItemAdapter listSeriesItemAdapter;

	private String seriesUrl;
	private View gridLayout, listLayout;
	private DramaRst dramaRst;
	/** 当前播放url */
	private String currentPlayUrl;
	private ColorBallProgressView seriesLoading;

	public static final Fragment newInstances(String seriesUrl, String currentPlayUrl) {
		Fragment fragment = new VideoSeriesFragment();
		Bundle bundle = new Bundle();
		bundle.putString("seriesUrl", seriesUrl);
		bundle.putString("currentPlayUrl", currentPlayUrl);
		fragment.setArguments(bundle);
		return fragment;
	}

	public VideoSeriesFragment() {
		super();
		EventBus.getDefault().register(this);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		contentView = inflater.inflate(R.layout.video_series, null);

		this.seriesUrl = getArguments().getString("seriesUrl");
		this.currentPlayUrl = getArguments().getString("currentPlayUrl");

		initViews();

		if (FoneUtil.isNetOk(getActivity())) {
			gridLayout.setVisibility(View.GONE);
			listLayout.setVisibility(View.GONE);
			seriesLoading.setVisibility(View.VISIBLE);
			requestSeries(seriesUrl);
		}
		return contentView;
	}

	private void initViews() {
		seriesGridView = (GridView) contentView.findViewById(R.id.cache_tv_gv);
		seriesTab = (NoScrollGridView) contentView.findViewById(R.id.cache_gridview_tab);
		seriesListView = (ListView) contentView.findViewById(R.id.cache_tv_lv);
		gridLayout = contentView.findViewById(R.id.video_series_cache_gridmode_layout);
		listLayout = contentView.findViewById(R.id.video_series_cache_listmode_layout);
		seriesLoading = (ColorBallProgressView) contentView.findViewById(R.id.series_loading);
	}

	/**
	 * 更新数据
	 * 
	 * @return void
	 * @throws
	 */
	private void updateData() {
		Activity activity = getActivity();
		if (activity == null) {
			return;
		}
		if (dramaRst.cntsList != null && dramaRst.cntsList.size() > 0) {
			if (dramaRst.cntsList.get(0).showtyp == 0) {// 规则显示剧集
				gridLayout.setVisibility(View.VISIBLE);
				listLayout.setVisibility(View.GONE);
				dramaRst.cntsList.get(0).isChecked = true;// 默认选中第一tab
				if (seriesTabItemAdapter != null) {
					seriesTabItemAdapter.setData(dramaRst.cntsList);
				} else {
					if (getActivity() != null) {
						seriesTabItemAdapter = new GridSeriesTabItemAdapter(dramaRst.cntsList, false);
						seriesTab.setAdapter(seriesTabItemAdapter);
					}
				}
				refreshTabView();
				seriesTab.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
						if (dramaRst == null || dramaRst.cntsList == null) {
							return;
						}
						for (Cnts cnts : dramaRst.cntsList) {
							cnts.isChecked = false;
						}
						Cnts cnts = dramaRst.cntsList.get(arg2);
						cnts.isChecked = true;
						seriesTabItemAdapter.notifyDataSetChanged();
						// 显示当前tab下的所有剧集
						if (cnts != null && cnts.cntList != null && cnts.cntList.size() > 0) {
							showRuleSeries(cnts);
						} else {
							// 显示请求对话框
							gridLayout.setVisibility(View.GONE);
							listLayout.setVisibility(View.GONE);
							seriesLoading.setVisibility(View.VISIBLE);
							requestSeries(cnts.url);
						}
					}
				});
				// 显示第一个tab下的所有剧集
				showRuleSeries(dramaRst.cntsList.get(0));
			} else {
				// 不规则显示
				showUnRuleSeries();
			}
		}
	}

	/**
	 * 显示当前Cnts下的剧集(规则剧集)
	 * 
	 * @param cnts
	 * @return void
	 * @throws
	 */
	private void showRuleSeries(Cnts cnts) {
		seriesLoading.setVisibility(View.GONE);
		if (cnts.cntList != null && cnts.cntList.size() > 0) {
			gridLayout.setVisibility(View.VISIBLE);
			listLayout.setVisibility(View.GONE);
			if (gridSeriesItemAdapter != null) {
				gridSeriesItemAdapter.setData(cnts.cntList, currentPlayUrl);
			} else {
				if (getActivity() != null) {
					gridSeriesItemAdapter = new GridSeriesItemAdapter(cnts.cntList, currentPlayUrl);
					seriesGridView.setAdapter(gridSeriesItemAdapter);
				}
			}
			seriesGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					if (getActivity() != null) {
						FonePlayerActivity activity = (FonePlayerActivity) getActivity();
						if (activity.isBuffering()) {
							return;
						}
						DramaRst.Cnt cnt = (Cnt) gridSeriesItemAdapter.getItem(arg2);
						if (!FoneUtil.getCIdByUrl(cnt.url).equals(gridSeriesItemAdapter.getCurrentPlayCId()) && FoneUtil.isNetOkWithToast(getActivity())) {
							VideoPlayerMessage msg = new VideoPlayerMessage();
							msg.what = VideoPlayerMessage.MESSGAE_CHANGE_VIDEO;
							msg.obj = new ChangeVideoEvent(cnt.url, false, false, false);
							EventBus.getDefault().post(msg);
						}
					}
				}
			});
		} else {
			requestSeries(cnts.url);
		}
	}

	/**
	 * 显示非规则剧集
	 * 
	 * @param cnts
	 * @return void
	 * @throws
	 */
	private synchronized void showUnRuleSeries() {
		seriesLoading.setVisibility(View.GONE);
		// 非规则剧集
		List<DramaRst.Cnt> dramas = new ArrayList<DramaRst.Cnt>();
		for (DramaRst.Cnts cnts : dramaRst.cntsList) {
			if (cnts != null && cnts.cntList != null) {
				dramas.addAll(cnts.cntList);
			}
		}
		// 不规则显示
		gridLayout.setVisibility(View.GONE);
		listLayout.setVisibility(View.VISIBLE);
		if (listSeriesItemAdapter == null && getActivity() != null) {
			listSeriesItemAdapter = new ListSeriesItemAdapter(dramas, currentPlayUrl);
			seriesListView.setAdapter(listSeriesItemAdapter);
			seriesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					if (getActivity() != null) {
						FonePlayerActivity activity = (FonePlayerActivity) getActivity();
						if (activity.isBuffering()) {
							return;
						}
						DramaRst.Cnt cnt = (Cnt) listSeriesItemAdapter.getItem(arg2);
						if (!FoneUtil.getCIdByUrl(cnt.url).equals(listSeriesItemAdapter.getCurrentPlayCId()) && FoneUtil.isNetOkWithToast(getActivity()) && FoneUtil.isNetOkWithToast(getActivity())) {
							VideoPlayerMessage msg = new VideoPlayerMessage();
							msg.what = VideoPlayerMessage.MESSGAE_CHANGE_VIDEO;
							msg.obj = new ChangeVideoEvent(cnt.url, false, false, false);
							EventBus.getDefault().post(msg);
						}
					}
				}
			});
		} else {
			listSeriesItemAdapter.setData(dramas);
		}
	}

	/**
	 * 请求对应tab下的剧集
	 * 
	 * @param cnts
	 * @return void
	 * @throws
	 */
	private void requestSeries(String url) {
		L.v(TAG, "请求剧集---");
		if (TextUtils.isEmpty(url)) {
			return;
		}
		Request.getInstance().drama(FoneUtil.handleUrl(url), new Callback<DramaRst>() {
			@Override
			public void onSuccess(DramaRst t) {
				if (destory) {
					return;
				}
				Activity activity = getActivity();
				if (activity == null) {
					return;
				}
				if (t == null) {
					seriesLoading.setVisibility(View.GONE);
					return;
				}
				if (t.result == 0) {
					if (dramaRst == null) {
						dramaRst = t;
						if (dramaRst.cntsList != null && dramaRst.cntsList.size() > 0) {
							updateData();
						}
					} else {

						if (dramaRst.cntsList == null || t.rp == null) {
							return;
						}

						// 数据返回了
						if (dramaRst.cntsList.get(t.rp.p - 1).cntList == null) {
							dramaRst.cntsList.get(t.rp.p - 1).cntList = new ArrayList<DramaRst.Cnt>();
						}
						dramaRst.cntsList.get(t.rp.p - 1).cntList.clear();
						dramaRst.cntsList.get(t.rp.p - 1).cntList.addAll(t.cntsList.get(t.rp.p - 1).cntList);
						// 显示规则剧集
						if (dramaRst.cntsList.get(0).showtyp == 0) {
							showRuleSeries(dramaRst.cntsList.get(t.rp.p - 1));
						} else {
							showUnRuleSeries();
						}
					}
					if (dramaRst.cntsList != null && dramaRst.cntsList.size() > t.rp.p) {
						if (dramaRst.cntsList.get(0).showtyp != 0) {
							// 不规则剧集继续请求
							requestSeries(dramaRst.cntsList.get(t.rp.p).url);
						}
					}
				} else {
					// 出错了
					if (t.error != null && !TextUtils.isEmpty(t.error.errormsg)) {
						Toast.makeText(getActivity(), t.error.errormsg, Toast.LENGTH_SHORT).show();
					}
				}
			}

			@Override
			public void onFailure(Error error) {
				if (destory) {
					return;
				}
				seriesLoading.setVisibility(View.GONE);
				L.v(TAG, "requestSeries onFailure " + error.getReason());
				// if (error.isNetworkError() && getActivity() != null) {
				// Toast.makeText(getActivity(),
				// R.string.player_network_not_stable,
				// Toast.LENGTH_SHORT).show();
				// } else if (getActivity() != null) {
				// Toast.makeText(getActivity(), error.getReason(),
				// Toast.LENGTH_SHORT).show();
				// }
			}
		});

	}

	/**
	 * 更新分页选择滑动条
	 * 
	 * @return void
	 * @throws
	 */
	public void refreshTabView() {
		Activity activity = getActivity();
		if (activity == null) {
			return;
		}
		seriesTabItemAdapter.notifyDataSetChanged();
		seriesTab.setNumColumns(dramaRst.cntsList.size());
		// width是否也需要取余
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) (ScreenUtil.dp2px(78) * dramaRst.cntsList.size()), ScreenUtil.dp2px(50));
		seriesTab.setLayoutParams(params);
	}

	/**
	 * eventbus事件
	 * 
	 * @return void
	 * @throws
	 */
	public void onEventMainThread(VideoPlayerMessage msg) {
		if (destory) {
			return;
		}
		switch (msg.what) {
		case VideoPlayerMessage.MESSGAE_CHANGE_VIDEO:// 切换视频
			ChangeVideoEvent event = (ChangeVideoEvent) msg.obj;
			// 当前播放url
			if (gridSeriesItemAdapter != null) {
				gridSeriesItemAdapter.setCurrentPlayUrl(event.xyzPlayUrl);
			}
			if (listSeriesItemAdapter != null) {
				listSeriesItemAdapter.setCurrentPlayUrl(event.xyzPlayUrl);
			}
			L.v(TAG, "receiver message MESSGAE_CHANGE_VIDEO xyzPlayUrl = " + event.xyzPlayUrl);
			this.currentPlayUrl = event.xyzPlayUrl;
			break;
		case VideoPlayerMessage.MESSGAE_CHANGE_FROM:// 切换来源
			From from = (From) msg.obj;
			dramaRst = null;
			this.seriesUrl = from.durl;
			gridLayout.setVisibility(View.GONE);
			listLayout.setVisibility(View.GONE);
			seriesLoading.setVisibility(View.VISIBLE);
			requestSeries(seriesUrl);
			break;
		default:
			break;
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		EventBus.getDefault().unregister(this);
		contentView = null;
		if (seriesTab != null) {
			seriesTab.removeAllViewsInLayout();
			seriesTab = null;
		}
		if (seriesGridView != null) {
			seriesGridView.removeAllViewsInLayout();
			seriesGridView = null;
		}
		if (seriesListView != null) {
			seriesListView.removeAllViewsInLayout();
			seriesListView = null;
		}
		seriesTabItemAdapter = null;
		gridSeriesItemAdapter = null;
		listSeriesItemAdapter = null;
		seriesUrl = null;
		gridLayout = null;
		listLayout = null;
		dramaRst = null;
		currentPlayUrl = null;
		seriesLoading = null;
	}

	public void onEventMainThread(Message msg) {
		switch (msg.what) {
		case StorageModule.MSG_ADD_CACHE_SUCCESS:// 缓存添加完成更新列表
			if (gridSeriesItemAdapter != null) {
				gridSeriesItemAdapter.notifyDataSetChanged();
			}
			if (listSeriesItemAdapter != null) {
				listSeriesItemAdapter.notifyDataSetChanged();
			}
			break;
		default:
			break;
		}
	}

}
